﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Write.Applications.Commands.ReportCommand;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers.ReportCommandHandlers
{
    public class CreateReportCommandHandlers : IRequestHandler<CreateReportCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public CreateReportCommandHandlers(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(CreateReportCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var model = mapper.Map<Report>(request);

            model.Del = false;

            result.data = await db.Insertable(model).ExecuteCommandAsync();

            if (result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "添加报工信息成功";

                // 假设 CreateReportCommand 中有 PackagingPlanId 字段
                int packagingPlanId = request.PackagingPlanId;

                // 根据 PackagingPlanId 统计 HegeNum 的数量
                var sumHegeNum = await db.Queryable<Report>()
                                         .Where(r => r.PackagingPlanId == packagingPlanId)
                                         .SumAsync<int?>(r => r.HegeNum);

                // 如果没有找到相关数据，sumHegeNum 可能为 null，这里处理为 0
                int totalHegeNum = sumHegeNum.HasValue ? sumHegeNum.Value : 0;

                var SumPackagingPlan = await db.Queryable<PackagingPlan>().Where(p => p.PackagingPlanId == packagingPlanId).SumAsync<int?>(p => p.PlannedProduction);

                var pack = await db.Queryable<PackagingPlan>()
                   .FirstAsync(p => p.PackagingPlanId == request.PackagingPlanId);

                if (sumHegeNum >= SumPackagingPlan)
                {
                    pack.isload = 2;
                    await db.Updateable<PackagingPlan>(pack).ExecuteCommandAsync();
                }
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "添加报工信息失败";
            }



            return result;
        }
    }
}
